class FileItem {
  final int? id;
  final String name;
  final String path;
  final String minioObjectName;
  final int size;
  final String mimeType;
  final int userId;
  final DateTime uploadedAt;
  final DateTime? updatedAt;
  final bool isFolder;
  final String? parentPath;

  FileItem({
    this.id,
    required this.name,
    required this.path,
    required this.minioObjectName,
    required this.size,
    required this.mimeType,
    required this.userId,
    required this.uploadedAt,
    this.updatedAt,
    this.isFolder = false,
    this.parentPath,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'path': path,
      'minio_object_name': minioObjectName,
      'size': size,
      'mime_type': mimeType,
      'user_id': userId,
      'uploaded_at': uploadedAt.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
      'is_folder': isFolder ? 1 : 0,
      'parent_path': parentPath,
    };
  }

  factory FileItem.fromMap(Map<String, dynamic> map) {
    return FileItem(
      id: map['id']?.toInt(),
      name: map['name'] ?? '',
      path: map['path'] ?? '',
      minioObjectName: map['minio_object_name'] ?? '',
      size: map['size']?.toInt() ?? 0,
      mimeType: map['mime_type'] ?? '',
      userId: map['user_id']?.toInt() ?? 0,
      uploadedAt: DateTime.parse(map['uploaded_at']),
      updatedAt: map['updated_at'] != null ? DateTime.parse(map['updated_at']) : null,
      isFolder: (map['is_folder'] ?? 0) == 1,
      parentPath: map['parent_path'],
    );
  }

  FileItem copyWith({
    int? id,
    String? name,
    String? path,
    String? minioObjectName,
    int? size,
    String? mimeType,
    int? userId,
    DateTime? uploadedAt,
    DateTime? updatedAt,
    bool? isFolder,
    String? parentPath,
  }) {
    return FileItem(
      id: id ?? this.id,
      name: name ?? this.name,
      path: path ?? this.path,
      minioObjectName: minioObjectName ?? this.minioObjectName,
      size: size ?? this.size,
      mimeType: mimeType ?? this.mimeType,
      userId: userId ?? this.userId,
      uploadedAt: uploadedAt ?? this.uploadedAt,
      updatedAt: updatedAt ?? this.updatedAt,
      isFolder: isFolder ?? this.isFolder,
      parentPath: parentPath ?? this.parentPath,
    );
  }

  String get sizeFormatted {
    if (size < 1024) return '${size}B';
    if (size < 1024 * 1024) return '${(size / 1024).toStringAsFixed(1)}KB';
    if (size < 1024 * 1024 * 1024) return '${(size / (1024 * 1024)).toStringAsFixed(1)}MB';
    return '${(size / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
  }

  bool get isImage => mimeType.startsWith('image/');
  bool get isVideo => mimeType.startsWith('video/');
  bool get isAudio => mimeType.startsWith('audio/');
  bool get isDocument => ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].contains(mimeType);
}